<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2019/2/25
 * Time: 10:11
 */

namespace app\login\model;


use app\lib\exception\ParameterException;
use Driver\Cache\Redis;
use think\Exception;

class Account extends BaseModel
{
    public function getHost($name)
    {
        return self::where('name', '=', $name)
            ->value('host');
    }
    # 通过name获取所有的标识
    public function getSign($name)
    {
        $redis_hash_key = config('redis.account').$name;
        $sign_redis = Redis::hget($redis_hash_key);
        $sign = null;
        if(count($sign_redis) !== 0 || array_key_exists('id', $sign_redis) == true){
            $sign = $sign_redis;
        }else{
            try{
                $sign_mysql = self::where('name', '=', $name)
                    ->find()
                    ->toArray();
                $sign = $sign_mysql;
            }catch (Exception $e){
                throw new ParameterException([
                    'msg' => '尝试获取的name不存在'
                ]);
            }
        }
        if($sign['host_d'] == '' || $sign['host_d'] == null){
            $host_d = false;
        }else{
            $host_d = true;
        }
        if($sign['host_f'] == '' || $sign['host_f'] == null){
            $host_f = false;
        }else{
            $host_d = true;
        }
        $sign_arr = explode('%', $sign['sign']);
        return [
            'arr' => $sign_arr,
            'info' => $sign,
            'host_d' => $host_d,
            'host_f' => $host_f,
        ];
    }
    # 删除或更新Account表中对应的sign字段
    public function addOrUpdateSign($name, $sign_str)
    {
        return self::where('name', '=', $name)
            ->update(['sign' => $sign_str]);
    }

    public function updateDataToRedis($name)
    {
        $data = self::where('name', '=', $name)
            ->find()
            ->toArray();
        return $data;
    }

    public function sign()
    {
        return $this->hasMany('SignService', 'user_id', 'id');
    }

    public function everySignData($name)
    {
        return self::with([
            'sign' => function($query) use ($name){
                $query->where('user_id', '=', $name);
            }
        ]);
    }

}